package com.bkhc.umc.auth.service;

import com.bkhc.common.annotation.ApiOperation;
import com.bkhc.umc.service.RoleSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RequestMappingHandlerMapping mapping;
    @Autowired
    private RoleSerivce roleSerivce;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 返回本次访问需要的权限，可以有多个权限
     * @param o
     * @return
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) {
        FilterInvocation obj = (FilterInvocation) o;
        HandlerExecutionChain hanler =null;
        try {
            hanler = mapping.getHandler(obj.getRequest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String[] values = new String[0];
        if(hanler != null){

        HandlerMethod handlerMethod  = (HandlerMethod)hanler.getHandler();
        ApiOperation apiOpreation = handlerMethod.getMethod().getAnnotation(ApiOperation.class);

        if(apiOpreation!=null){
            String operationCode = apiOpreation.code();
            List<String> roleCodes = roleSerivce.getRoleCode(operationCode);
            int size = roleCodes.size();
            values = new String[size];
            for (int i = 0; i < size; i++) {
                values[i] = roleCodes.get(i);
            }
        }

        }
        return SecurityConfig.createList(values);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
